package com.caochenlei.proxy.dynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class UserDaoProxy {
    private UserDao userDao;

    public UserDaoProxy(UserDao userDao) {
        this.userDao = userDao;
    }

    public UserDao createUserDao() {
        Class<? extends UserDao> clazz = userDao.getClass();
        UserDao ud = (UserDao) Proxy.newProxyInstance(
                clazz.getClassLoader(),
                clazz.getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        Object result;
                        if ("delete".equals(method.getName())) {
                            System.out.println("UserDaoProxy 权限校验 ...");
                            result = method.invoke(userDao, args);
                            System.out.println("UserDaoProxy 日志记录 ...");
                        } else {
                            result = method.invoke(userDao, args);
                        }
                        return result;
                    }
                });
        return ud;
    }
}
